<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 300px;
        height: 300px;
        border: 1px solid purple;
        background-color: skyblue;
        margin: 50px 0;
      }
    </style>
  </head>
  <body>
    <button>发送ajax</button>
    <div class="box"></div>
    <script>
      var btn = document.querySelector('button')
      var box = document.querySelector('.box')
      btn.onclick = function () {
        var xhr = new XMLHttpRequest()
        // 设置响应体数据类型
        xhr.responseType = 'json'
        xhr.open('post', 'http://127.0.0.1:8080/sever')
        // application/x-www-form-urlencoded 编码格式  参数的格式为key=value&key=value
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
        // 自定义设置请求头
        xhr.setRequestHeader('name', 'zsls')
        xhr.send('a=100&b=200&c=300') // post请求体
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4) {
            if (xhr.status >= 200 && xhr.status < 300) {
              // console.log(xhr.response)
              // box.innerHTML = xhr.response
              // 1.手动转化格式
              // let res = JSON.parse(xhr.response)
              // box.innerHTML = res.name + ':' + res.age
              // 自动转换
              box.innerHTML = xhr.response.name + ':' + xhr.response.age
            }
          }
        }
      }
    </script>
  </body>
</html>
